import 'package:dio/dio.dart' as DIO;
import 'package:dy_download_utils/bean_download_result.dart';
import 'package:dy_download_utils/dailogs.dart';
import 'package:dy_download_utils/enum_connect_state.dart';
import 'package:dy_download_utils/http_client.dart';
import 'package:dy_download_utils/state_request.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';

const BASE_HOST0 = 'http://marklife.love/dytk/request2';
const BASE_HOST1 = 'http://marklife.love/dytk/request';

class DyController extends GetxController {
  static DyController get to => Get.find();

  final requestInfoState = ConnectState.none.obs;
  final requestInfoResult = DownloadInfoResult.fromParams().obs;

  late TextEditingController urlController0;
  late TextEditingController urlController1;

  TextEditingController get urlC0 => urlController0;

  TextEditingController get urlC1 => urlController1;

  final shareTextLive = ''.obs;

  // final List<> = 0.obs;
  // final progressLive = 0.obs;

  final progressMapLive = <String, int>{}.obs;

  @override
  void onInit() {
    super.onInit();

    urlController0 = TextEditingController();
    urlController1 = TextEditingController();
  }

  ///发送添加mark请求
  void requestDownloadWebPage(int index, String dyUrl) async {
    requestInfoState.value = ConnectState.waiting;
    requestInfoState.refresh();

    String url = BASE_HOST0;
    if (index == 0) {
      url = BASE_HOST0;
    } else if (index == 1) {
      url = BASE_HOST1;
    }

    var formData = DIO.FormData.fromMap({
      'url': dyUrl,
    });

    try {
      var response = await HttpManager.getInstance()
          .dio!
          .post(url, data: formData, onSendProgress: (int count, int data) {
        print('add mark count: $count, data: $data');
      });

      DownloadInfoResult result = DownloadInfoResult(response.data);

      if (result.err == RequestState.SUCCESS) {
        result.url = dyUrl;
        requestInfoResult.value = result;
        requestInfoResult.refresh();
        requestInfoState.value = ConnectState.done;
        requestInfoState.refresh();
      } else {
        requestInfoState.value = ConnectState.err;
        requestInfoState.refresh();
      }
    } catch (e) {
      requestInfoState.value = ConnectState.err;
      requestInfoState.refresh();
      print(e);
    }
  }

  void download1(String urlSuffix, String name) async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/" + name;
    String fileUrl = "https://www.chenshiyang.com/dytk/downloader$urlSuffix";
    await DIO.Dio().download(fileUrl, savePath,
        onReceiveProgress: (count, total) {
      int progress = (count / total * 100) ~/ 1;
      DyController.to.progressMapLive[urlSuffix] = progress;
      DyController.to.progressMapLive.refresh();
    });
    final result = await ImageGallerySaver.saveFile(savePath);
    if (result['isSuccess']) {
      DyController.to.progressMapLive[urlSuffix] = -1;
      DyController.to.progressMapLive.refresh();
      popDialog(
          Container(
            child: Center(
              child: RichText(
                text: TextSpan(
                  text: '视频 ',
                  style: const TextStyle(
                    fontSize: 18.0,
                    color: Colors.black87,
                  ),
                  children: [
                    TextSpan(
                      text: name,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.deepPurple,
                        fontSize: 20.0,
                      ),
                    ),
                    const TextSpan(
                      text: ' 已经完成下载。',
                      style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.black87,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ), onPositiveTap: () {
        Get.back();
      });
    } else {
      DyController.to.progressMapLive[urlSuffix] = -1;
      DyController.to.progressMapLive.refresh();
      popDialog(
          Container(
            child: Text(
              '下载失败',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.black87,
              ),
            ),
          ), onPositiveTap: () {
        Get.back();
      });
    }
  }

  void download0(String url, String name) async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/" + name;
    String downloadUrl = "http://marklife.love/dytk/download";
    await DIO.Dio().download(downloadUrl, savePath,
        options:
            DIO.Options(method: "POST", extra: {"title": name, "url": url}),
        onReceiveProgress: (count, total) {
      int progress = (count / total * 100) ~/ 1;
      DyController.to.progressMapLive[url] = progress;
      DyController.to.progressMapLive.refresh();
    });
    final result = await ImageGallerySaver.saveFile(savePath);
    if (result['isSuccess']) {
      DyController.to.progressMapLive[url] = -1;
      DyController.to.progressMapLive.refresh();
      popDialog(
          Container(
            child: Center(
              child: RichText(
                text: TextSpan(
                  text: '视频 ',
                  style: const TextStyle(
                    fontSize: 18.0,
                    color: Colors.black87,
                  ),
                  children: [
                    TextSpan(
                      text: name,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.deepPurple,
                        fontSize: 20.0,
                      ),
                    ),
                    const TextSpan(
                      text: ' 已经完成下载。',
                      style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.black87,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ), onPositiveTap: () {
        Get.back();
      });
    } else {
      DyController.to.progressMapLive[url] = -1;
      DyController.to.progressMapLive.refresh();
      popDialog(
          Container(
            child: Text(
              '下载失败',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.black87,
              ),
            ),
          ), onPositiveTap: () {
        Get.back();
      });
    }
  }
}
